var Bill = function () {
    return Bill.fn.init();
}

// Declare
Bill.fn = Bill.prototype = {
	// Autocom
    input:null,
    selected_ctn:null,
    parent:null,
    item:null, // template show result
	update:null, // show result duoc chon
	index:null, // so thu tu result duoc chon

	// set price
	payment:null,

	// Init
    init:function() {

    	// Khoi tao doi pay mayment
    	var obj = $('#payment');
    	this.payment = {
    		deposit: obj.find('#BillGetPayment'),
    		sum: obj.find('#BillSum'),
    		discount: obj.find('#BillDiscount'),
    		remaining: obj.find('#BillRemaining')
    	};
    },

    /**
	 *	Set Price
	 **/
	setPrice:function() {
		var _this = this;
		var sum = 0;
		var remaining = 0;

		// Tinh sum product
		var product = this.update.find('tr');
		if(product.length > 0) {
			product.each(function(){
				var price = $(this).find('.pprice').html();
				price = price.replaceAll( ['.', ',', ' '], '');
				if(!isNumeric(price)) price = 1;

				var $amount = $(this).find('.amount');
				var amount = $amount.val().replaceAll( ['.', ',', ' '], '');

				if( !isNumeric(amount)) {
					amount = parseFloat(amount);
					if(!isNumeric(amount)){
						amount = 1;
					}
				}

				$amount.val(amount).attr('value', amount);

				sum += parseInt(price) * parseInt( amount );
			});
		}

		// tinh giam gia
		var deposit = (this.payment.deposit.val()).replaceAll( ['.', ',', ' '], '');
		var discount = (this.payment.discount.val()).replaceAll( ['.', ',', ' '], '');

		if( !isNumeric(deposit)) {
			deposit = parseFloat(deposit);
			if( !isNumeric(deposit)) {
				deposit = 0;
			}
		}
		deposit = parseInt(deposit);


		if( !isNumeric(discount)) {
			discount = parseFloat(discount);
			if( !isNumeric(discount)) {
				discount = 0;
			}
		}

		discount = parseInt(discount);

		discount = discount < 0 ? 0 : ( discount > 100 ? 100 : discount);

		remaining = sum - (( sum * discount )/100 + deposit);

		// Truong hop remaining < 0
		if( remaining < 0 )
		{
			remaining = 0;
			deposit = sum - (( sum * discount )/100);

			if(deposit < 0) deposit = 0;
		}

		// show payment
		this.payment.deposit.val(deposit).attr('value', formatMoney(deposit));
		this.payment.discount.val(discount).attr('value', discount);
		this.payment.sum.val(sum).attr('value', formatMoney(sum));
		this.payment.remaining.val(remaining).attr('value', formatMoney(remaining));
	},

	/**
	 *	Start auto
	 **/
    startAuto: function(options){
		if(options) {
			this.input = options.input ? options.input : null;
			this.selected_ctn = options.selected_ctn != 'undefined' ? options.selected_ctn : null;
			this.input = options.input != 'undefined' ? options.input : null;
			this.item = options.item != 'undefined' ? options.item : null;
			this.update = options.update != 'undefined' ? options.update : null;
			this.index = options.index != 'undefined' ? options.index : null;

			this.autocom();
		}
    },

	/**
	 *	Autocomplate
	 **/
	timeout: 300,
	timer: null,
    autocom:function()
    {
    	var _this = this;

	    this.input.keyup(function(e) {

			clearTimeout( _this.timer );

	        _this.timer = setTimeout(function(){

				_this.search('/products/search?q=');

	        }, _this.timeout );

	    }); // end key up
    },

    /**
	 *	Search
	 **/
	search: function(url)
	{
		var _this = this;

		if(url && url.length > 0) {

			// Xoa errors
			_this.input.parent().find('.error-message').remove();

			var q = _this.input.val();
			var datanone = _this.input.attr('data-none');

			// Kiem tra xem input co du lieu hay khong
	       	if( q.trim().length > 0 ) {

				// Get data
				getAjax(url + q + '&datanone=' + datanone , true, function(resp){

		            if(resp.items.length > 0 )
		            {
		                html = '';
		                resp.items.forEach(function(it) {
		                    html += '<li id="'+ it.P.id +'" title="'+ it.P.name +'" price="'+it.P.price+'">'+ it.P.name +'</li>';
		                });

		                html = $(html);
		                _this.selected_ctn.html(html);
		            }
		            else
		                _this.selected_ctn.html('<li class="empty">Not Found</li>');

					// Bind event click li
					_this.selected_ctn.find('li').click(function(event){
						event.preventDefault();
		               	event.stopPropagation();

		               	//_this.closeStop();
						_this.input.val('').attr('value' , '');

						var li = $(this);
						if( !li.hasClass('empty') ) {
							// add data-none
							datanone += li.attr('id') + ',';
							_this.input.attr('data-none', datanone);

							_this.selected(event);
						}
					});

					_this.closeStart();
		        }); // end get data

	       	} else {
	 			//_this.selected_ctn.html('');
	       	}
       	}
	},


	/**
	 *	Selected
	 **/
	selected:function(event) {
		var _this = this;
		var obj = $(event.currentTarget);

		var id = obj.attr('id');

		var $product = this.item.clone();

		$product.find('.stt').html( _this.index );
		$product.find('input').each( function (){
	        var name = $(this).attr('name');
	        name = name.replace('[DetailBill]', '[DetailBill][' + _this.index + ']');

	        $(this).attr('name', name );
	    });

		var hiddenid = $product.find('#DetailBillProductId');
	    hiddenid.val(id).attr('value', id);
	    hiddenid.before(obj.html());
	    $product.find('.pprice').html(formatMoney(parseFloat(obj.attr('price'))));
	    $product.find('.remove').attr('pid', id);

	    this.update.append($product);

		// remove li da chon
	    obj.remove();

		// Bind event close khi click ra ngoai
		this.closeStart();

		this.index++;

		this.setPrice();
	},

	/**
	 *	Remove selected
	 **/
	removeSelected: function(obj) {
		if(obj) {
			var id = obj.attr('pid');
			var datanone = this.input.attr('data-none');
			datanone = datanone.replace(id + ',', '');
			this.input.attr('data-none', datanone);
			obj.closest('tr').remove();

			this.setPrice();
			return true;
		}
		return false;
	},

	/**
	 *	close start
	 **/
	closeStart:function() {
		var _this = this;
		$('body').unbind().click(function(event){
			event.stopPropagation();
			clearTimeout( _this.timer );
			_this.selected_ctn.html('');
			_this.input.val('').attr('value' , '');
		});
	},

	/**
	 *	close stop
	 **/
	closeStop:function() {
		$('body').unbind();
	},
}

var bill = new Bill();

